
/* ==============================================================================
*
*   Copyright (c) 2010, Pierre Favier
*   All rights reserved.
*
*   NTasking is free software: you can redistribute it and/or modify it
*   under the terms of the GNU General Public License as published by the
*   Free Software Foundation.
*
*   Redistribution and use in source and binary forms, with or without
*   modification, are permitted provided that the following conditions
*   are met:
*
*   -   Redistributions of source code must retain the above copyright notice,
*       this list of conditions and the following disclaimer.
*
*   -   Redistributions in binary form must reproduce the above
*       copyright notice, this list of conditions and the following
*       disclaimer in the documentation and/or other materials
*       provided with the distribution.
*
*   THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
*   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*   BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
*   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
*   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
*   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
*   TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
*   THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*   SUCH DAMAGE.
*
* ============================================================================== */

using System;
using System.Threading;
using NTasking.ValidationTests.ACATS_3_0.Support;
using NUnit.Framework;
using Rhino.Mocks;

namespace NTasking.ValidationTests.ACATS_3_0.C9
{

    [TestFixture(Description = "")]
    public class C9740013 : ValidationTest
    {

        private const double AllotedTime = Impdef.SwitchToNewTask;


        internal class CalculationCancelled : Exception
        {
        }


        private static int Count = 1234;


        private static void LengthyCalculation()
        {
            // Simulate a non-convergin calculation
            while (true)
            {
                Count = (Count + 1)%10;
                if (!Equal(Count, Count)) // Condition always false.
                    break;
                Ada.Delay(0.0); // abort completion point 
            }
        }


        internal static bool Equal(int left, int right)
        {
            return left == right;
        }


        internal class TimedCalculation : ValidationTestTask
        {

            [Entry]
            internal Action<double> Calculation { get; private set; }


            internal TimedCalculation(IValidationTestResult result)
                : base(result)
            {
            }


            protected override void Body()
            {
                DateTime delayTime;

                while (true)
                {
                    Select(s => s.

                        Accept(Calculation, Do: (timeLimit) =>
                        {

                            // We have to construct an "until" time artificially 
                            // as we have no control over when the test will be run
                            delayTime = DateTime.Now.AddSeconds(timeLimit);

                            // Asynchronous select is tested here

                            Delay.Select(delayTime, () =>
                            {
                                // This is executed after LengthyCalculation aborted.
                                throw new CalculationCancelled();
                            }).
                            ThenAbort(() =>
                            {
                                // Delay expires before complete, so this call is aborted.
                                LengthyCalculation();
                                // Check that the whole of the abortable part is aborted,
                                // not just the statement in the abortable part that was
                                // executing at the time
                                Result.TestFailed();
                            });
                        },
                        Exception: (ex) =>
                        {
                            if (!(ex is CalculationCancelled))
                                return true;

                            if (C9740013.Count == 1234)
                                // Abortable part did no execute
                                Result.TestFailed();

                            return false;
                        }).

                    Or.

                        Terminate

                    );
                }
            }
            protected override void Exception(Exception ex)
            {
                // Unexpected exception in Timed_Calculation task
                Result.TestFailed();
            }

        }


        [Test(Description =
            "Check that the abortable part of an asynchronous select statementt" +
            "is aborted if it does not complete before the triggering statementt" +
            "completes, where the triggering statement is a delay_relativet" +
            "statement and check that the sequence of statements of the triggering t" +
            "alternative is executed after the abortable part is left.")]
        public void Test()
        {
            IValidationTestResult result = Mocks.DynamicMock<IValidationTestResult>();

            TimedCalculation timed = null;

            Ada.Declare(() =>
            {
                timed = new TimedCalculation(result);

                // Setup text expectations

                Expect.Call(result.TestFailed).Repeat.Never();

                Mocks.ReplayAll();
            },
            Begin: () =>
            {
                // Start test execution
                timed.Calculation(AllotedTime);
            },
            Exception: (ex) =>
            {
                if (ex is CalculationCancelled)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            });

        }

    }

}
